<template>
	<view class="container">
		<!-- 标题区域 -->
		<view class="header">
			<text class="title">学生分数统计</text>
			<text class="subtitle">记录学生成长点滴，激励进步</text>
		</view>

		<!-- 筛选区域 -->
		<view class="filter-section glass-card">
			<view class="filter-row">
				<!-- 学科选择 -->
				<picker mode="selector" :range="subjectOptions" @change="changeSubject" range-key="label">
					<view class="filter-item active-filter">
						<uni-icons type="compose" size="16" color="#4d90fe"></uni-icons>
						<text class="filter-text">{{selectedSubject.label || '选择学科'}}</text>
						<uni-icons type="arrowdown" size="16" color="#4d90fe"></uni-icons>
					</view>
				</picker>

				<!-- 日期筛选 -->
				<view class="date-filter-group">
					<view class="date-filter-option" :class="{active: dateFilterType === 'all'}"
						@click="changeDateFilterType('all')">
						全部时间
					</view>
					<view class="date-filter-option" :class="{active: dateFilterType === 'range'}"
						@click="showDatePicker = true">
						选择范围
					</view>
				</view>
			</view>

			<!-- 日期范围显示 -->
			<view class="date-range-display" v-if="dateFilterType === 'range' && (dateRange.start || dateRange.end)">
				<text>{{dateRange.start || '开始日期'}} 至 {{dateRange.end || '结束日期'}}</text>
			</view>

			<!-- 日期选择器 -->
			<view class="date-picker-modal" v-if="showDatePicker">
				<view class="date-picker-content">
					<view class="date-picker-header">
						<text>选择日期范围</text>
						<uni-icons type="close" size="20" @click="showDatePicker = false"></uni-icons>
					</view>
					<view class="date-picker-body">
						<picker mode="date" fields="day" @change="(e) => dateRange.start = e.detail.value">
							<view class="date-picker-item">
								<text>开始日期: {{dateRange.start || '请选择'}}</text>
							</view>
						</picker>
						<picker mode="date" fields="day" @change="(e) => dateRange.end = e.detail.value">
							<view class="date-picker-item">
								<text>结束日期: {{dateRange.end || '请选择'}}</text>
							</view>
						</picker>
					</view>
					<view class="date-picker-footer">
						<button class="cancel-btn" @click="showDatePicker = false">取消</button>
						<button class="confirm-btn" @click="confirmDateRange">确定</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 学科分数分布图表 -->

		<view class="glass-card chart-container" v-if="activeChartTab === 'subject'">
			<view class="section-title" @click="activeChartTab = 'student'">学科分数分布(切换)</view>
			<qiun-data-charts type="ring" :opts="ringChartOpts" :chartData="subjectChartData" />
		</view>

		<view class="glass-card chart-container" v-if="activeChartTab === 'student'">
			<view class="section-title" @click="activeChartTab = 'subject'">学生得分排名(切换)</view>
			<scroll-view scroll-x class="chart-scroll"
				v-if="studentChartData.series && studentChartData.series[0].data.length > 6">
				<view class="chart-wrapper">
					<qiun-data-charts type="mount" :chartData="studentChartData" :ontouch="true"
						:opts="mountChartOpts" />
				</view>
			</scroll-view>
			<qiun-data-charts v-else type="mount" :chartData="studentChartData" />
		</view>

		<!-- 功能卡片 -->
		<view class="card-group">
			<view class="glass-card action-card" @click="navigateToAddScore">
				<view class="card-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
					<uni-icons type="plus" size="28" color="#fff"></uni-icons>
				</view>
				<view class="card-content">
					<text class="card-title">添加评分</text>
					<text class="card-desc">记录学生表现</text>
				</view>
				<uni-icons type="forward" size="20" color="#999"></uni-icons>
			</view>

			<view class="glass-card action-card" @click="navigateToHistory">
				<view class="card-icon" style="background: linear-gradient(135deg, #a6c1ee 0%, #fbc2eb 100%);">
					<uni-icons type="list" size="28" color="#fff"></uni-icons>
				</view>
				<view class="card-content">
					<text class="card-title">历史记录</text>
					<text class="card-desc">查看所有评分记录</text>
				</view>
				<uni-icons type="forward" size="20" color="#999"></uni-icons>
			</view>
		</view>

		<!-- 分数排行榜 -->
		<view class="glass-card ranking-container">
			<view class="section-title">学生分数排行榜</view>
			<view class="ranking-tabs">
				<view v-for="(tab, index) in rankingTabs" :key="index" class="tab-item"
					:class="{active: activeRankingTab === tab.value}" @click="changeRankingTab(tab.value)">
					{{tab.label}}
				</view>
			</view>

			<view class="ranking-list">
				<view v-for="(student, index) in filteredRankingList" :key="student.studentId" class="ranking-item"
					:class="{'top-3': index < 3}" @click="show(student.userId)">
					<view class="rank-index">
						{{index + 1}}
					</view>
					<image :src="student.aver || '/static/aver1.jpg'" class="avatar"></image>
					<view class="student-info">
						<text class="student-name">{{student.studentName}}</text>
						<text class="grade">{{student.grade}}</text>
					</view>
					<view class="score-info">
						<text class="score-value">{{student.totalScore}}分</text>
						<text class="score-count">{{student.scoreCount}}次</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
	export default {
		data() {
			return {
				grade: '',
				dateRange: {
					start: '',
					end: ''
				},
				showDatePicker: false,
				dateFilterType: 'all', // 'all'表示全部时间，'range'表示日期范围,
				scores: [],
				students: [],
				selectedMonth: '',
				activeRankingTab: 'total',
				activeChartTab: 'subject', // 默认显示学科分数分布
				subjectOptions: [], // 初始化为空数组，等待后端数据填充
				selectedSubject: {
					label: '全部学科',
					value: ''
				},
				rankingTabs: [{
						label: '总分',
						value: 'total'
					},
					{
						label: '加分次数',
						value: 'count'
					}
				],
				studentChartWidth: 750, // 学生图表初始宽度
				ringChartOpts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [5, 5, 5, 5],
					dataLabel: true,
					enableScroll: false,
					legend: {
						show: true,
						position: "right",
						lineHeight: 25
					},
					title: {
						name: "",
						fontSize: 15,
						color: "#666666"
					},
					subtitle: {
						show: false,
						name: "",
						fontSize: 0
					},
					extra: {
						ring: {
							ringWidth: 60,
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: false,
							borderWidth: 3,
							borderColor: "#FFFFFF"
						}
					}
				},
				mountChartOpts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 15, 0, 5],
					enableScroll: true,
					legend: {},
					xAxis: {
						disableGrid: true,
						itemCount: 4,
						scrollShow: true
					},
					yAxis: {
						data: [{
							min: 0
						}]
					},
					extra: {
						mount: {
							type: "mount",
							widthRatio: 1.5,
							borderWidth: 2,
							linearType: "opacity",
							linearOpacity: 0.1
						}
					}
				},
				subjectChartData: {},
				studentChartData: {}
			};
		},
		computed: {
			filteredRankingList() {
				let list = [...this.students];

				// 按不同排序方式排序
				if (this.activeRankingTab === 'total') {
					list.sort((a, b) => b.totalScore - a.totalScore);
				} else if (this.activeRankingTab === 'average') {
					list.sort((a, b) => (b.totalScore / b.scoreCount) - (a.totalScore / a.scoreCount));
				} else {
					list.sort((a, b) => b.scoreCount - a.scoreCount);
				}

				return list;
			}
		},
		onLoad(options) {
			this.grade = options.grade;
			this.fetchData();
		},
		onShow() {
			this.fetchData();
		},
		methods: {
			show(studentId) {
				uni.navigateTo({
					url: "/pages/scoreHistroyOne/scoreHistroyOne?studentId=" + studentId
				})
			},
			changeDateFilterType(type) {
				this.dateFilterType = type;
				this.filterScores();
			},
			applyDateFilter() {
				this.filterScores();
			},
			confirmDateRange() {
				this.showDatePicker = false;
				this.dateFilterType = 'range';
				this.filterScores();
			},
			// 切换图表类型
			changeChartTab(tab) {
				this.activeChartTab = tab;
			},
			// 修改筛选方法
			 filterScores() {
			    let filtered = [...this.scores];
			
			    // 学科筛选（使用动态学科）
			    if (this.selectedSubject.value) {
			      filtered = filtered.filter(s => s.scoreType === this.selectedSubject.value);
			    }
			
			    // 日期筛选
			    if (this.dateFilterType === 'range' && (this.dateRange.start || this.dateRange.end)) {
			      filtered = filtered.filter(s => {
			        const scoreDate = this.formatTime(s.time);
			        return (
			          (!this.dateRange.start || scoreDate >= this.dateRange.start) &&
			          (!this.dateRange.end || scoreDate <= this.dateRange.end)
			        );
			      });
			    }
			
			    // 重新计算学生分数
			    this.students.forEach(student => {
			      const studentScores = filtered.filter(s => s.studentId === student.userId);
			      student.totalScore = studentScores.reduce((sum, s) => {
			        const scoreValue = parseInt(s.score) || 0;
			        // 根据role决定是加分还是减分
			        return s.role === 1 ? sum + scoreValue : sum - scoreValue;
			      }, 0);
			      student.scoreCount = studentScores.length;
			    });
			
			    // 更新图表
			    this.prepareChartData();
			  },
			async fetchData() {
				await this.fetchSubjectData(); // 先获取学科数据
				await this.fetchStudents();
			},
			fetchSubjectData() {
				uni.request({
					url: `${globalVariable}/getSubjectByGrade?grade=${this.grade}`,
					success: (res) => {
						if (res.data.status === 1) {
							const subjectData = res.data.data;
							if (subjectData && subjectData.subjects) {
								// 解析学科字符串，如"语文,数学"
								const subjects = subjectData.subjects.split(',');

								// 构建学科选项，包含"全部学科"选项
								this.subjectOptions = [{
										label: '全部学科',
										value: ''
									},
									...subjects.map(subject => ({
										label: subject.trim(),
										value: subject.trim()
									}))
								];

								// 重置选中学科为"全部学科"
								this.selectedSubject = this.subjectOptions[0];
							}
						}
					}
				});
			},
			fetchScoreData() {
				uni.request({
					url: `${globalVariable}/getScoresByGrade?grade=${this.grade}`,
					success: (res) => {
						if (res.data.status === 1) {
							this.scores = res.data.data || [];
							this.processScoreData();
							// 确保在这里调用计算分数
							this.calculateStudentScores();
							this.prepareChartData();
						}
					}
				});
			},
			fetchStudents() {
				uni.request({
					url: `${globalVariable}/getStudentsByGrade?grade=${this.grade}`,
					success: (res) => {
						if (res.data.status === 1) {
							this.students = (res.data.data || []).map(student => ({
								...student,
								aver: student.aver ? `${globalVariable}/get/${student.aver}` :
									null,
								totalScore: 0,
								scoreCount: 0
							}));
							this.fetchScoreData();
						}
					}
				});
			},
			processScoreData() {
				this.scores = this.scores.map(score => {
					// 确保score字段是数字类型
					return {
						...score,
						score: parseInt(score.score) || 0, // 强制转换为数字
						timeFormatted: this.formatTime(score.time)
					};
				});
			},
			calculateStudentScores() {
				this.students.forEach(student => {
					// 检查关联字段是否匹配
					const studentScores = this.scores.filter(s => s.studentId == student.userId);
					student.totalScore = studentScores.reduce((sum, s) => {
						const scoreValue = parseInt(s.score) || 0;
						// 根据role决定是加分还是减分
						return s.role === 1 ? sum + scoreValue : sum - scoreValue;
					}, 0);
					student.scoreCount = studentScores.length;
				});
			},
			prepareChartData() {
				// 准备学科分数分布图表数据
				const subjectScores = {};
				this.scores.forEach(score => {
					const subject = score.scoreType || '其他';
					const scoreValue = parseInt(score.score) || 0;
					// 根据role决定是加分还是减分
					const adjustedScore = score.role === 1 ? scoreValue : -scoreValue;
					subjectScores[subject] = (subjectScores[subject] || 0) + adjustedScore;
				});

				this.subjectChartData = {
					series: [{
						data: Object.keys(subjectScores).map(subject => ({
							name: subject,
							value: subjectScores[subject]
						}))
					}]
				};

				// 准备学生得分排名图表数据
				const sortedStudents = [...this.students].sort((a, b) => b.totalScore - a.totalScore);
				const sortedStudents2 = [...this.students];
				this.studentChartData = {
					series: [{
						name: '学生得分',
						data: sortedStudents2.map(student => ({
							name: student.studentName,
							value: student.totalScore
						}))
					}]
				};

				// 计算学生图表宽度
				if (sortedStudents.length > 6) {
					this.studentChartWidth = sortedStudents.length * 180;
				} else {
					this.studentChartWidth = 750;
				}
			},
			changeSubject(e) {
				this.selectedSubject = this.subjectOptions[e.detail.value];
				this.filterScores();
			},
			changeMonth(e) {
				this.selectedMonth = e.detail.value;
				this.filterScores();
			},
			changeRankingTab(tab) {
				this.activeRankingTab = tab;
			},
			formatTime(time) {
				if (!time) return '';
				const date = new Date(time);
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			},
			navigateToAddScore() {
				uni.navigateTo({
					url: `/pages/scoreAdd/scoreAdd?grade=${this.grade}`
				});
			},
			navigateToHistory() {
				uni.navigateTo({
					url: `/pages/scoreHistory/scoreHistory?grade=${this.grade}&scoreData=` + JSON.stringify(this
						.scores)
				});
			}
		}
	};
</script>
<style lang="scss" scoped>
	/* 日期选择器美化 */
	/* 图表切换选项卡样式 */
	.chart-tabs {
		display: flex;
		padding: 0;
		overflow: hidden;

		.tab-item {
			flex: 1;
			text-align: center;
			padding: 20rpx;
			font-size: 28rpx;
			color: #666;
			position: relative;
			transition: all 0.3s;

			&.active {
				color: #4d90fe;
				font-weight: bold;
				background: rgba(77, 144, 254, 0.1);

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 60rpx;
					height: 4rpx;
					background: #4d90fe;
					border-radius: 2rpx;
				}
			}
		}
	}

	/* 图表容器样式 */
	.chart-container {
		padding: 20rpx;

		.section-title {
			font-size: 28rpx;
			color: #666;
			padding: 20rpx 20rpx 10rpx;
		}

		.chart-scroll {
			width: 100%;
			height: 400rpx;
			white-space: nowrap;

			.chart-wrapper {
				display: inline-block;
				height: 400rpx;
			}
		}
	}

	.date-picker-content {
		width: 100%;
		background: #fff;
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
	}

	.date-picker-header {
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #f0f0f0;
		background: #f9f9f9;

		text {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.date-picker-body {
		padding: 30rpx;

		.date-picker-item {
			padding: 25rpx 0;
			border-bottom: 1px solid #f5f5f5;
			display: flex;
			justify-content: space-between;
			align-items: center;

			text {
				font-size: 28rpx;
				color: #333;
			}

			&::after {
				content: ">";
				color: #ccc;
				font-size: 24rpx;
			}
		}
	}

	.date-picker-footer {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		border-top: 1px solid #f0f0f0;

		button {
			flex: 1;
			margin: 0 10rpx;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 30rpx;
			border-radius: 12rpx;
			transition: all 0.3s;

			&:active {
				opacity: 0.8;
			}
		}

		.cancel-btn {
			background: #f8f8f8;
			color: #666;
		}

		.confirm-btn {
			background: linear-gradient(135deg, #4d90fe 0%, #1a73e8 100%);
			color: #fff;
			box-shadow: 0 4rpx 12rpx rgba(77, 144, 254, 0.3);
		}
	}

	/* 筛选区域样式 */
	.filter-item.active-filter {
		background: rgba(77, 144, 254, 0.1);
		border: 1px solid rgba(77, 144, 254, 0.3);
		color: #4d90fe;
	}

	.filter-text {
		margin: 0 10rpx;
	}

	.date-filter-group {
		display: flex;
		border-radius: 48rpx;
		overflow: hidden;
		border: 1px solid #eee;
	}

	.date-filter-option {
		padding: 16rpx 24rpx;
		font-size: 28rpx;
		background: #f8f8f8;
		color: #666;

		&.active {
			background: rgba(77, 144, 254, 0.1);
			color: #4d90fe;
			font-weight: bold;
		}
	}

	.date-range-display {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		margin-top: 20rpx;
		background: #f9f9f9;
		border-radius: 12rpx;
		font-size: 26rpx;
	}

	.date-picker-modal {
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.date-picker-content {
		background: #fff;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.date-picker-header {
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #eee;
	}

	.date-picker-body {
		padding: 30rpx;
	}

	.date-picker-item {
		padding: 20rpx 0;
		border-bottom: 1px solid #f5f5f5;
	}

	.date-picker-footer {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
	}

	.confirm-btn,
	.cancel-btn {
		padding: 0 40rpx;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 28rpx;
		border-radius: 30rpx;
	}

	.confirm-btn {
		background: #4d90fe;
		color: #fff;
	}

	.cancel-btn {
		background: #f8f8f8;
		color: #666;
	}

	.container {
		padding: 30rpx;
		min-height: 100vh;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
		background-image:
			radial-gradient(circle at 10% 20%, rgba(255, 15, 51, 0.1) 0%, transparent 20%),
			radial-gradient(circle at 90% 80%, rgba(8, 255, 111, 0.1) 0%, transparent 20%);
	}

	/* 毛玻璃卡片基础样式 */
	.glass-card {
		background: rgba(255, 255, 255, 0.7);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(255, 255, 255, 0.4);
		transition: all 0.3s ease;
		margin-bottom: 30rpx;
	}

	.header {
		margin-bottom: 40rpx;
		text-align: center;

		.title {
			display: block;
			font-size: 42rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}

		.subtitle {
			display: block;
			font-size: 26rpx;
			color: #888;
		}
	}

	.filter-section {
		padding: 20rpx;

		.filter-row {
			display: flex;
			justify-content: space-between;

			.filter-item {
				display: flex;
				align-items: center;
				padding: 16rpx 24rpx;
				background: rgba(255, 255, 255, 0.8);
				border-radius: 48rpx;
				font-size: 28rpx;
				color: #666;

				text {
					margin-right: 10rpx;
				}
			}
		}
	}

	.chart-container {
		padding: 20rpx;

		.section-title {
			font-size: 28rpx;
			color: #666;
			padding: 20rpx 20rpx 10rpx;
		}

		.charts-box {
			// width: 100%;
			height: 400rpx;
		}
	}

	.card-group {
		display: flex;
		flex-direction: column;
		gap: 30rpx;
	}

	.action-card {
		display: flex;
		align-items: center;
		padding: 30rpx;

		.card-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		}

		.card-content {
			flex: 1;

			.card-title {
				display: block;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 6rpx;
			}

			.card-desc {
				display: block;
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	.ranking-container {
		padding: 0 0 20rpx;

		.section-title {
			font-size: 28rpx;
			color: #666;
			padding: 20rpx 30rpx;
			border-bottom: 1px solid rgba(0, 0, 0, 0.05);
		}

		.ranking-tabs {
			display: flex;
			padding: 20rpx 30rpx;
			border-bottom: 1px solid rgba(0, 0, 0, 0.05);

			.tab-item {
				flex: 1;
				text-align: center;
				padding: 12rpx 0;
				font-size: 26rpx;
				color: #666;
				position: relative;

				&.active {
					color: #4d90fe;
					font-weight: bold;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 60rpx;
						height: 4rpx;
						background: #4d90fe;
						border-radius: 2rpx;
					}
				}
			}
		}

		.ranking-list {
			.ranking-item {
				display: flex;
				align-items: center;
				padding: 20rpx 30rpx;
				border-bottom: 1px solid rgba(0, 0, 0, 0.05);

				&:last-child {
					border-bottom: none;
				}

				&.top-3 {
					.rank-index {
						color: #ff9a9e;
						font-weight: bold;
						font-size: 36rpx;
					}
				}

				.rank-index {
					width: 50rpx;
					text-align: center;
					font-size: 32rpx;
					color: #999;
					margin-right: 20rpx;
				}

				.avatar {
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
					margin-right: 20rpx;
				}

				.student-info {
					flex: 1;

					.student-name {
						display: block;
						font-size: 30rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 4rpx;
					}

					.grade {
						display: block;
						font-size: 24rpx;
						color: #999;
					}
				}

				.score-info {
					display: flex;
					flex-direction: column;
					align-items: flex-end;

					.score-value {
						font-size: 28rpx;
						font-weight: bold;
						color: #4d90fe;
						margin-bottom: 4rpx;
					}

					.score-count {
						font-size: 22rpx;
						color: #999;
					}
				}
			}
		}
	}
</style>